/**
 * 
 */
package cc.monggo.web.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cc.monggo.web.filter.response.ServletOutputStreamResponseWrapper;

/**
 * @author fangjinsong
 *
 */
public class ServletOutputStreamFilterDemo implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)req;
		HttpServletResponse httpResponse = (HttpServletResponse)resp;
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		ServletOutputStreamResponseWrapper wrapper = new ServletOutputStreamResponseWrapper(httpResponse, buffer);
		chain.doFilter(httpRequest, wrapper);
		
		wrapper.flushBuffer();
		String originData = new String(buffer.toByteArray());
		String updatedData = originData.replaceAll("12", "13");
		System.out.println(updatedData);
		OutputStream output = httpResponse.getOutputStream();
		output.write(updatedData.getBytes());
		output.flush();
		output.close();
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
